<template>
    <div ref="wrapRef"></div>
</template>
<script lang="ts" setup>
import { ElRef, Nullable } from '../../types'
import {
    Ref,
    useAttrs,
    ref,
    unref,
    nextTick,
    watch,
    onBeforeUnmount,
    onDeactivated
} from 'vue'

import Vditor from 'vditor'
import 'vditor/dist/index.css'

import { onMountedOrActivated } from '../../hooks/onMountedOrActivated'
const props = defineProps({
    height: { type: Number, default: 360 },
    value: { type: String, default: '' }
})
const emit = defineEmits(['change', 'get', 'update:value'])

const wrapRef = ref<ElRef>(null);
const vditorRef = ref(null) as Ref<Nullable<Vditor>>
const initedRef = ref(false)

const valueRef = ref(props.value || '')

const instance = {
    getVditor: (): Vditor => vditorRef.value!
}

instance.getVditor()?.setTheme('classic')
// 监听数据变化
watch(
    () => props.value,
    (v) => {
        if (v !== valueRef.value) {
            instance.getVditor()?.setValue(v)
        }
        valueRef.value = v
    }
)

const init = () => {
    const wrapEl = unref(wrapRef) as HTMLElement
    if (!wrapEl) return
    const bindValue = { ...useAttrs(), ...props }
    const insEditor = new Vditor(wrapEl, {
        theme: 'classic',
        lang: 'zh_CN',
        mode: 'sv',
        fullscreen: {
            index: 520
        },
        preview: {
            actions: []
        },
        input: (v) => {
            valueRef.value = v
            emit('update:value', v)
            emit('change', v)
        },
        after: () => {
            nextTick(() => {
                insEditor.setValue(valueRef.value)
                vditorRef.value = insEditor
                initedRef.value = true
                emit('get', instance)
            });
        },
        blur: () => {
            // unref(vditorRef)?.setValue(props.value)
        },
        ...bindValue,
        cache: {
            enable: false
        }
    });
}

watch(
    () => props.height,
    (v) => {
        console.log(props.height, '-=-=-')
        console.log(v, '-=')
    }
)

function destroy() {
    const vditorInstance = unref(vditorRef)
    if (!vditorInstance) return
    try {
        vditorInstance?.destroy?.()
    } catch (error) { }
    vditorRef.value = null
    initedRef.value = false
}

onMountedOrActivated(init)

onBeforeUnmount(destroy)
onDeactivated(destroy)
</script>
